﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WAD.Model;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;

namespace WAD.DAL
{
    /// <summary>
    /// 收藏数据库操作类
    /// </summary>
    public class DaoCollect : DAO
    {
        /// <summary>
        /// 添加一条收藏
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static bool Add(MCollect m)
        {
            String sql = "insert into collect(article_id,[type],[user_id],url)values(@article_id,@type,@user_id,@url)";
            Database db = GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@type", DbType.Int32, m.type);
            db.AddInParameter(cmd, "@article_id", DbType.Int32, m.article_id);
            db.AddInParameter(cmd, "@url", DbType.String, m.url);
            db.AddInParameter(cmd, "@user_id", DbType.Int32, m.user_id);
            return db.ExecuteNonQuery(cmd) > 0;
        }

        /// <summary>
        /// 判断是否已经添加过过了该条帖子
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public static bool IsCollect(MCollect m)
        {
            String sql = "select count(id) from collect where [user_id] = @user_id and [type] = @type and article_id = @article_id and url = @url";
            Database db = GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@type", DbType.Int32, m.type);
            db.AddInParameter(cmd, "@article_id", DbType.Int32, m.article_id);
            db.AddInParameter(cmd, "@url", DbType.String, m.url);
            db.AddInParameter(cmd, "@user_id", DbType.Int32, m.user_id);
            return (int)db.ExecuteScalar(cmd) > 0;
        }

        /// <summary>
        /// 删除一条收藏
        /// </summary>
        /// <param name="id">广告id</param>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public static bool Delete(int id, int userId)
        {
            String sql = "delete collect where id = " + id + " and user_id = " + userId;
            return ExecuteNonQuery(sql) > 0;
        }



        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页显示的总条数</param>
        /// <returns></returns>
        public static PageData GetList(int pageIndex, int pageSize, int userId)
        {
            String fieldList = "id,CONVERT(varchar(20), [date], 20) [date],article_logo,article_title,article_click,article_id,[type],url";
            String orderBy = "id desc";
            String where = "[user_id] = " + userId;
            String tableName = "v_collect";
            return GetPageList(fieldList, orderBy, pageIndex, pageSize, where, tableName);
        }
    }
}
